//
//  UIViewController+Helper.m
//  Water
//
//  Created by reyzhang on 2021/2/3.
//  Copyright © 2021 myjs. All rights reserved.
//

#import "UIViewController+Helper.h"

@implementation UIViewController (Helper)

/*!
 根据storyboard 来创建对象实例
 */
+ (instancetype)createInstanceWithSbName:(NSString *)sbName {
    if ([sbName isEqualToString:@""]) {
        sbName = @"Main";
    }
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:sbName bundle:nil];
    NSString *identifier = NSStringFromClass([self class]);
    
    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:identifier];
    return vc;
}


/*!
 使用默认的Main.storyboard来创建实例
 */
+ (instancetype)createInstanceWithMainSB {
    return [self createInstanceWithSbName:@""];
}


/*!
 点击view 隐藏键盘
 */

- (void)setupForDismissKeyboard
{
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    
    __weak UIViewController *weakSelf = self;
    
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    
    ////通知观察键盘弹出动作，给视图添加手势
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [weakSelf.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [weakSelf.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}




/**
 移除自身
 */
- (void)removeSelfWithAnimation {
    CATransition *animation = [CATransition animation];
    animation.duration = 0.3f;
    animation.type = kCATransitionFade;
    animation.removedOnCompletion = YES;
    [self.view.window.layer addAnimation:animation forKey:nil];
}
@end
